package cn.fd.controller;

import cn.fd.domain.Account;
import cn.fd.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;

/**
 * @Author 田俊龙
 * @Date 2022/1/7
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @RequestMapping("/login")
    public String login(String username,String password){
        if ("t".equals(username)&&"1".equals(password)){
            return "redirect:/account/findAll";
        }
        return "login";
    }
    /**
     * 查询所有的方法
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model) throws IOException {
        List<Account> list = accountService.findAll();
      /*  ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("allAccount");*/
        model.addAttribute("list",list);
        return "allAccount";
    }

    //跳转到add页面
    @RequestMapping("/toAdd")
    public String ToAdd(){
        return "addAccount";
    }

    /**
     * 保存账户的方法
     * @param account
     * @return
     */
    @RequestMapping("/add")
    public String add(Account account) throws IOException {
        accountService.save(account);
        return "redirect:/account/findAll";//重定向到findAll页面
    }

    //跳转到更新页面
    @RequestMapping("/toUpdate")
    public String toUpdate(Model model,int id){
        Account account = accountService.findById(id);
        model.addAttribute("account",account);
        return "updateAccount";
    }

    /**
     * 修改账户的方法
     * @param account
     * @return
     */
    @RequestMapping("/update")
    public String update(Account account) throws IOException {
        accountService.update(account);
        return "redirect:/account/findAll";//重定向到findAll页面
    }

    //删除账户
    @RequestMapping("/delete/{accountId}")
    public String delete(@PathVariable("accountId") int id){
        accountService.delete(id);
        return "redirect:/account/findAll";//重定向到findAll页面
    }
}
